<template>
<div class="search">
  <!-- 顶部搜索导航 -->
  <form class="search_form" action="/">
  <van-search
    v-model="searchValue"
    show-action
    placeholder="请输入搜索关键词"
    @search="onSearch"
    @cancel="isShowResult = false"
    @focus="isShowResult = false"
  />
</form>
<!-- 搜索结果 -->
<search-result
  v-if="isShowResult"
  :search-text="searchValue"
></search-result>
<!-- 搜索历史 -->
<search-history
  v-else-if="!searchValue"
  :history="history"
  @search="onSearch"
></search-history>
<!-- 搜索联想建议 -->
<search-suggest
  v-else
  :search-text="searchValue"
  @search="onSearch"
></search-suggest>
</div>
</template>

<script>
import searchHistory from './components/searchHistory'
import searchResult from './components/searchResult'
import searchSuggest from './components/searchSuggest'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'search',
  data () {
    return {
      searchValue: '',
      isShowResult: false,
      // 页面一进来就获取本地数据，如果本地没有数据就为空数组
      // （如果不设置，为null,子组件对history使用了数组方法，会报错）
      history: getItem('hmtt_history') || []
    }
  },

  created () {

  },

  methods: {
    // 点击搜索的时候
    onSearch (val) {
      if (val === '') return
      // console.log('点击了确定')
      // 查找搜索历史是已经包含当前值
      const index = this.history.indexOf(val)
      if (index !== -1) {
        // 若包含，先删除
        this.history.splice(index, 1)
      }
      // 向前添加搜索历史
      this.history.unshift(val)

      this.searchValue = val
      this.isShowResult = true
    },
    // 点击取消的时候
    onCancel () {
      // console.log('点击了取消')
      this.$router.go(-1)
    }

  },
  watch: {
    history (nVal) {
      setItem('hmtt_history', nVal)
    }

  },
  components: {
    searchHistory,
    searchResult,
    searchSuggest
  }
}
</script>

<style scoped lang='less'>
  .search {
    .van-search {
      background: #3295F9;
    }
    .van-search_action {
      color: #fff;
    }
    .search_form {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 2;
    }
  }
</style>
